﻿using Microsoft.Extensions.Configuration;
using KeepAccounts.Common.Extensions;
using System;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace KeepAccounts.Common.Utilities
{
    public class ManagerConfig
    {
        //private static readonly IHostEnvironment _hostingEnvironment = ObjectContainer.Current.Resolve<IHostEnvironment>();
        //private static IConfigurationRoot configuration;


        public ManagerConfig()
        {
            //var builder = new ConfigurationBuilder()
            // //.SetBasePath(_hostingEnvironment.ContentRootPath)
            // .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            // //.AddJsonFile($"appsettings.{_hostingEnvironment.EnvironmentName}.json", optional: true)
            // .AddEnvironmentVariables();
            //configuration = builder.Build();
        }


        public static string GetManagerConfig(string keyName)
        {
            #region 老的读取配置文件
            try
            {

                var ENVIRONMENT = System.Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

                var builder = new ConfigurationBuilder()
                // .SetBasePath(_hostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 .AddJsonFile($"appsettings.{ENVIRONMENT}.json", optional: true)
                 .AddEnvironmentVariables();
                var configuration = builder.Build();
                return configuration[keyName].ToString();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("KeepAccounts.Common.Utilities.ManagerConfig.GetManagerConfig:", ex);
                return string.Empty;
            }



            #endregion


        }
        public static T GetManagerSection<T>(string sectionName) where T : class, new()
        {
            try
            {
                var builder = new ConfigurationBuilder()
                //.SetBasePath(_hostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                // .AddJsonFile($"appsettings.{_hostingEnvironment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
                var configuration = builder.Build();
                var t = new T();
                configuration.Bind(sectionName, t);
                return t;
                //return JsonConvert.SerializeObject(configuration.GetSection(sectionName));
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("KeepAccounts.Common.Utilities.ManagerConfig.GetManagerSection:", ex);
                return null;
            }

        }



    }
}
